import * as createTradition from '../services/createTradition';
import { browserHistory } from 'dva/router';
import pathToRegexp from 'path-to-regexp';
import { message } from 'antd';

export default {
  namespace: 'createTradition',
  state: {
    createLoading: false,
    action: "",
    creatives: []
  },
  reducers: {
    save(state, action) {
      return {
        ...state,
        ...action.payload
      }
    },
    setLoading(state, action) {
      return {
        ...state,
        ...action.payload
      }
    },
    setAction(state, action) {
      return {
        ...state,
        ...action.payload
      }
    },
    setCreatives(state, action) {
      return {
        ...state,
        ...action.payload
      }
    }
  },
  effects: {
    *submit({ payload }, { call, put }) {
      // console.log(payload)
      const { data } = yield call(createTradition.submit, { payload });
      // yield put({ type: 'setLoading', payload: { createLoading: false }});

      if (data.success) {
        message.success('创建成功', 3);
        browserHistory.push('/page/packetList');
        return;
      }
      message.error(data.msg || '系统错误，请重试', 3);
    },
    *update({ payload }, { call, put }) {
      // console.log(payload)
      const { data } = yield call(createTradition.update, { payload });
      // yield put({ type: 'setLoading', payload: { createLoading: false }});
      //
      if (data.success) {
        message.success('创建成功', 3);
        browserHistory.push('/page/packetList');
        return;
      }
      message.error(data.msg || '系统错误，请重试', 3);
    },
    *fetch({ payload }, { call, put }) {
      const { data } = yield call(createTradition.fetch, { payload });
      if (data) {
        const result = data.data;
        yield put({
          type: 'save',
          payload: {
            ...result
          }
        })
      }
    }
  },
  subscriptions: {
    setup({ dispatch, history }) {
      return history.listen(({ pathname, query }) => {
        const edit = pathToRegexp('/page/packet/edit/2/:id').exec(pathname);
        dispatch({
          type: 'setAction',
          payload: {
            createLoading: false,
            action: '',
            creatives: []
          }
        });

        if (edit) {
          dispatch({
            type: 'fetch',
            payload: JSON.stringify({
              id: edit[1]
            })
          });
          dispatch({
            type: 'setAction',
            payload: {
              action: 'edit',
              grpRemark: '',
              grpTitle: ''
            }
          })
        }
      })
    }
  }
};
